package plus.eadydo.gateway.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import plus.easydo.core.result.DataResult;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 授权拦截filter 基于统一鉴权中心
 * @author yuzhanfeng
 */
@Component
public class AuthFilterGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthFilterGatewayFilterFactory.config> {


    private static final String BEARER_TOKEN_TYPE = "Bearer ";

    private static final String NAME_KEY = "name";

    private static final String CLIENT_ID = "client_id";

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(NAME_KEY);
    }

    @Override
    public GatewayFilter apply(config config) {
        return (exchange,chain)->{
            List<String> tokenList = exchange.getRequest().getHeaders().get(config.getName());
            if (tokenList != null && !tokenList.isEmpty()) {
                String token = tokenList.get(0);
                token = token.replace(BEARER_TOKEN_TYPE, "");
//                Map<String, Object> result = oauthServerFeignClient.checkToken(token);
                Map<String, Object> result = new HashMap<>();
                if(result.get(CLIENT_ID) != null){
                    return chain.filter(exchange);
                }else {
                  return response(exchange,"访问失败，携带token无效或已过期");
                }
            }else{
                return response(exchange,"拒绝访问，没有携带token");
            }
        };


    }

    private Mono<Void> response(ServerWebExchange exchange, String message){
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return exchange.getResponse().writeWith(
                Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(DataResult.result(401,message,false)))));
    }


    public static class config{

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}



